package getools4me;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class UserManager {

	public static final String email_admin = "jpgtama@gmail.com";
	
	
	public static String getAdminEmail(){
		return email_admin;
	}
	
	public static boolean isStranger(String email){
		boolean is = true;
		if(email_admin.equals(email)){
			is = false;
		}
		return is;
	}
	
	public static boolean isStranger(User u){
		return u==null?true:isStranger(u.getEmail());
	}
	
	public static boolean isStranger(){
		UserService us = UserServiceFactory.getUserService();
		User user = us.getCurrentUser();
		return isStranger(user);
	}
	
	public static boolean isAdmin(){
		return !isStranger();
	}
	
	public static User getCurrentUser(){
		return UserServiceFactory.getUserService().getCurrentUser();
	}
	
	public static boolean isLogin(){
		return UserServiceFactory.getUserService().isUserLoggedIn();
	}
	
	public static String getLoginURL(HttpServletRequest request){
		String thisUrl = getRequestURLWithParameters(request);
		UserService us = UserServiceFactory.getUserService();
		String loginURL = us.createLoginURL(thisUrl);
		
		return loginURL;
	}
	public static String getLogoutURL(HttpServletRequest request){
		String thisUrl = getRequestURLWithParameters(request);
		UserService us = UserServiceFactory.getUserService();
		String logoutURL = us.createLogoutURL(thisUrl);
		return logoutURL;
	}
	
	public static String getRequestURLWithParameters(HttpServletRequest request){
		String thisUrl = request.getRequestURI();
		String url_param = "?";
		// get parameters
		@SuppressWarnings("unchecked")
		Enumeration<String> param_names = request.getParameterNames();
		while(param_names.hasMoreElements()){
			String name = param_names.nextElement();
			String value = request.getParameter(name);
			url_param+=name+"="+value;
			if(param_names.hasMoreElements()){
				url_param += "&";
			}
		}
		if(url_param.length()>1){
			thisUrl += url_param;
		}
		
		return thisUrl;
	}
	
	
	
}
